package jnpf.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.service.VisualdevService;
import jnpf.base.util.DynDicUtil;
import jnpf.base.util.VisualUtils;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.engine.service.FlowTaskService;
import jnpf.entity.ZXGL_XMCFZGBMJSEntity;
import jnpf.entity.ZXGL_XMCFZGBMJS_MingXiEntity;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.generater.util.GeneraterSwapUtil;
import jnpf.model.zxgl_xiangmufenjie.ZXGL_AI_ResponsibilityCallBack;
import jnpf.model.zxgl_xmcfzgbmjs.*;
import jnpf.service.ZXGL_XMCFZGBMJSService;
import jnpf.service.ZXGL_XMCFZGBMJS_MingXiService;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * ZXGL_XMCFZGBMJS
 *
 * @版本： V2.0
 * @版权： 河北交投智能交通技术有限责任公司
 * @作者： 数字交投项目组
 * @日期： 2025-03-19
 */
@Slf4j
@RestController
@Api(tags = "ZXGL_XMCFZGBMJS", value = "zxgl")
@RequestMapping("/ZXGL_XMCFZGBMJS")
public class ZXGL_XMCFZGBMJSController {


    @Autowired
    private DynDicUtil dynDicUtil;
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;

    @Autowired
    private VisualdevService visualdevService;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private ZXGL_XMCFZGBMJSService zXGL_XMCFZGBMJSService;

    @Autowired
    private ZXGL_XMCFZGBMJS_MingXiService zXGL_XMCFZGBMJS_MingXiService;


    /**
     * 列表
     *
     * @param zXGL_XMCFZGBMJSPagination
     * @return
     */
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZXGL_XMCFZGBMJSPagination zXGL_XMCFZGBMJSPagination) throws IOException {
        List<ZXGL_XMCFZGBMJSEntity> list = zXGL_XMCFZGBMJSService.getList(zXGL_XMCFZGBMJSPagination);
        //处理id字段转名称，若无需转或者为空可删除
        for (ZXGL_XMCFZGBMJSEntity entity : list) {
            entity.setOrganizeName(generaterSwapUtil.comSelectValues(entity.getOrganizeName()));
            entity.setDepartmentName(generaterSwapUtil.comSelectValues(entity.getDepartmentName()));
            entity.setZrr(generaterSwapUtil.userSelectValues(entity.getZrr()));
            entity.setSfzpr(dynDicUtil.getDicName(entity.getSfzpr(), "669876395320571525"));
            entity.setZpry(generaterSwapUtil.userSelectValues(entity.getZpry()));
            entity.setXmjl(generaterSwapUtil.userSelectValues(entity.getXmjl()));
            entity.setSfnbcxfp(dynDicUtil.getDicName(entity.getSfnbcxfp(), "669876395320571525"));
            entity.setSfqbjs(dynDicUtil.getDicName(entity.getSfqbjs(), "669876395320571525"));
        }
        List<ZXGL_XMCFZGBMJSListVO> listVO = JsonUtil.getJsonToList(list, ZXGL_XMCFZGBMJSListVO.class);
        for (ZXGL_XMCFZGBMJSListVO zXGL_XMCFZGBMJSVO : listVO) {
        }


        for (ZXGL_XMCFZGBMJSListVO vo : listVO) {
            FlowTaskEntity flowTaskEntity = flowTaskService.getInfoSubmit(vo.getId());
            if (flowTaskEntity != null) {
                vo.setFlowState(flowTaskEntity.getStatus());
            } else {
                vo.setFlowState(null);
            }
        }
        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zXGL_XMCFZGBMJSPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }


    /**
     * 创建
     *
     * @param zXGL_XMCFZGBMJSCrForm
     * @return
     */
    @PostMapping
    @Transactional
    public ActionResult create(@RequestBody @Valid ZXGL_XMCFZGBMJSCrForm zXGL_XMCFZGBMJSCrForm) throws DataException {
        String visualId = "667650650904992965";
        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        String mainId = RandomUtil.uuId();
        UserInfo userInfo = userProvider.get();
        ZXGL_XMCFZGBMJSEntity entity = JsonUtil.getJsonToBean(zXGL_XMCFZGBMJSCrForm, ZXGL_XMCFZGBMJSEntity.class);
        entity.setId(mainId);
        entity.setCreatorTime(new Date());
        entity.setZjid(mainId);
        entity.setTjzt(zXGL_XMCFZGBMJSCrForm.getStatus());
        zXGL_XMCFZGBMJSService.save(entity);

        if (zXGL_XMCFZGBMJSCrForm.getZxgl_xmcfzgbmjs_mingxiList() != null && zXGL_XMCFZGBMJSCrForm.getZxgl_xmcfzgbmjs_mingxiList().size() > 0) {
            List<ZXGL_XMCFZGBMJS_MingXiEntity> ZXGL_XMCFZGBMJS_MingXiList = JsonUtil.getJsonToList(zXGL_XMCFZGBMJSCrForm.getZxgl_xmcfzgbmjs_mingxiList(), ZXGL_XMCFZGBMJS_MingXiEntity.class);
            if (ZXGL_XMCFZGBMJS_MingXiList != null && ZXGL_XMCFZGBMJS_MingXiList.size() > 0) {
                for (ZXGL_XMCFZGBMJS_MingXiEntity entitys : ZXGL_XMCFZGBMJS_MingXiList) {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setMainid(entity.getId());
                    entitys.setCreatorTime(new Date());
                    zXGL_XMCFZGBMJS_MingXiService.save(entitys);
                }
            }
        }
        if (FlowStatusEnum.submit.getMessage().equals(zXGL_XMCFZGBMJSCrForm.getStatus())) {
            try {
                VisualUtils.submitFlowTask(visualdevEntity, mainId, zXGL_XMCFZGBMJSCrForm, userInfo, zXGL_XMCFZGBMJSCrForm.getCandidateList());
                FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(mainId);
                if (flowTaskEntity != null) {
                    flowTaskEntity.setTitle(zXGL_XMCFZGBMJSCrForm.getBt());
                    flowTaskEntity.setDataTable("zxgl_xmcfzgbmjs");
                    flowTaskService.update(flowTaskEntity);
                }
            } catch (WorkFlowException e) {
                e.printStackTrace();
            }
            return ActionResult.success("提交成功，请耐心等待");
        }
        return ActionResult.success("保存成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ActionResult<ZXGL_XMCFZGBMJSInfoVO> info(@PathVariable("id") String id) {
        ZXGL_XMCFZGBMJSEntity entity = zXGL_XMCFZGBMJSService.getInfo(id);
        ZXGL_XMCFZGBMJSInfoVO vo = JsonUtil.getJsonToBean(entity, ZXGL_XMCFZGBMJSInfoVO.class);

        //子表
        List<ZXGL_XMCFZGBMJS_MingXiEntity> ZXGL_XMCFZGBMJS_MingXiList = zXGL_XMCFZGBMJSService.GetZXGL_XMCFZGBMJS_MingXiList(id);
        for (ZXGL_XMCFZGBMJS_MingXiEntity zxgl_xmcfzgbmjs_mingxiEntity : ZXGL_XMCFZGBMJS_MingXiList) {

        }
        String userId = userProvider.get().getUserId();
        List<ZXGL_XMCFZGBMJS_MingXiEntity> list = ZXGL_XMCFZGBMJS_MingXiList.stream().filter(o -> o.getZrr() != null && o.getZrr().equals(userId)).collect(Collectors.toList());
        if (list != null && list.size() > 0) {
            vo.setZXGL_XMCFZGBMJS_MingXiList(JsonUtil.getJsonToList(list, ZXGL_XMCFZGBMJS_MingXiModel.class));
        } else {
            vo.setZXGL_XMCFZGBMJS_MingXiList(JsonUtil.getJsonToList(ZXGL_XMCFZGBMJS_MingXiList, ZXGL_XMCFZGBMJS_MingXiModel.class));
        }
        //副表
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZXGL_XMCFZGBMJSUpForm zXGL_XMCFZGBMJSUpForm) throws DataException {
        String visualId = "667650650904992965";
        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        UserInfo userInfo = userProvider.get();
        ZXGL_XMCFZGBMJSEntity entity = zXGL_XMCFZGBMJSService.getInfo(id);
        if (entity != null) {
            ZXGL_XMCFZGBMJSEntity subentity = JsonUtil.getJsonToBean(zXGL_XMCFZGBMJSUpForm, ZXGL_XMCFZGBMJSEntity.class);
            subentity.setTjzt(zXGL_XMCFZGBMJSUpForm.getStatus());
            zXGL_XMCFZGBMJSService.update(id, subentity);

            // QueryWrapper<ZXGL_XMCFZGBMJS_MingXiEntity> ZXGL_XMCFZGBMJS_MingXiqueryWrapper = new QueryWrapper<>();
            // ZXGL_XMCFZGBMJS_MingXiqueryWrapper.lambda().eq(ZXGL_XMCFZGBMJS_MingXiEntity::getMainid, entity.getId());
            // zXGL_XMCFZGBMJS_MingXiService.remove(ZXGL_XMCFZGBMJS_MingXiqueryWrapper);

            if (zXGL_XMCFZGBMJSUpForm.getZxgl_xmcfzgbmjs_mingxiList() != null && zXGL_XMCFZGBMJSUpForm.getZxgl_xmcfzgbmjs_mingxiList().size() > 0) {
                List<ZXGL_XMCFZGBMJS_MingXiEntity> ZXGL_XMCFZGBMJS_MingXiList = JsonUtil.getJsonToList(zXGL_XMCFZGBMJSUpForm.getZxgl_xmcfzgbmjs_mingxiList(), ZXGL_XMCFZGBMJS_MingXiEntity.class);
                for (ZXGL_XMCFZGBMJS_MingXiEntity entitys : ZXGL_XMCFZGBMJS_MingXiList) {
                    if (StringUtil.isEmpty(entitys.getId())) {
                        entitys.setId(RandomUtil.uuId());
                        entitys.setMainid(entity.getId());
                        entitys.setCreatorTime(new Date());
                        zXGL_XMCFZGBMJS_MingXiService.save(entitys);
                    } else {
                        zXGL_XMCFZGBMJS_MingXiService.updateById(entitys);
                    }
                }
            }


            if (FlowStatusEnum.submit.getMessage().equals(zXGL_XMCFZGBMJSUpForm.getStatus())) {
                try {
                    VisualUtils.submitFlowTask(visualdevEntity, id, subentity, userInfo, zXGL_XMCFZGBMJSUpForm.getCandidateList());
                    FlowTaskEntity flowTaskEntity = flowTaskService.getInfo(id);
                    if (flowTaskEntity != null) {
                        flowTaskEntity.setTitle(zXGL_XMCFZGBMJSUpForm.getBt());
                        flowTaskEntity.setDataTable("zxgl_xmcfzgbmjs");
                        flowTaskService.update(flowTaskEntity);
                    }
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
                return ActionResult.success("提交成功，请耐心等待");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZXGL_XMCFZGBMJSEntity entity = zXGL_XMCFZGBMJSService.getInfo(id);
        if (entity != null) {
            FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(id);
            if (taskEntity != null) {
                try {
                    flowTaskService.delete(taskEntity);
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
            }
            zXGL_XMCFZGBMJSService.delete(entity);
            QueryWrapper<ZXGL_XMCFZGBMJS_MingXiEntity> queryWrapperZXGL_XMCFZGBMJS_MingXi = new QueryWrapper<>();
            queryWrapperZXGL_XMCFZGBMJS_MingXi.lambda().eq(ZXGL_XMCFZGBMJS_MingXiEntity::getMainid, entity.getId());
            zXGL_XMCFZGBMJS_MingXiService.remove(queryWrapperZXGL_XMCFZGBMJS_MingXi);

        }
        return ActionResult.success("删除成功");
    }

    /**
     * 生成流水号并更新明细表
     *
     * @return
     */
    @GetMapping("/sequence/{id}")
    @Transactional
    public ActionResult sequence(@PathVariable("id") String id) {
        String prefix = "ZXGL-" + LocalDateTime.now().getYear() + "年-";
        String strNum = zXGL_XMCFZGBMJS_MingXiService.findMaxSequence(prefix);
        Long num;
        if (strNum == null) {
            num = 0l;
        } else {
            num = Long.parseLong(strNum);
        }
        List<ZXGL_XMCFZGBMJS_MingXiEntity> updateList = new ArrayList<>();
        List<ZXGL_XMCFZGBMJS_MingXiEntity> list = zXGL_XMCFZGBMJSService.GetZXGL_XMCFZGBMJS_MingXiList(id);
        for (ZXGL_XMCFZGBMJS_MingXiEntity entity : list) {
            if (entity.getJszt().equals("669883054189213317")) {
                String sequence = prefix + String.format("%04d", num);
                entity.setXmbh(sequence);
                updateList.add(entity);
                num++;
            }
        }
        boolean update = true;
        if (updateList.size() > 0) {
            update = zXGL_XMCFZGBMJS_MingXiService.updateBatchById(updateList);
        }

        if (update) {
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败");
        }

    }

    /**
     * 更新项目立项和明细表信息
     *
     * @param updateLX
     * @return
     */
//    @PostMapping("/updateLX")
//    @Transactional
//    public ActionResult updateLX(@RequestBody ZXGL_UpdateLX updateLX) throws DataException {
//        boolean update = zXGL_XMCFZGBMJSService.updateLiXiangInfo(updateLX.getTaskId());
//        if (update) {
//            return ActionResult.success("更新成功");
//        } else {
//            return ActionResult.fail("更新失败，数据不存在");
//        }
//    }


    /**
     * 更新项目立项和明细表信息
     *
     * @param updateInfo
     * @return
     */
    @PostMapping("/updateInfo")
    @Transactional
    public ActionResult updateInfo(@RequestBody ZXGL_UpdateInfo updateInfo) {
        log.info("updateInfo.getTaskId():===========================>" + updateInfo.getTaskId());
        zXGL_XMCFZGBMJSService.updateInfo(updateInfo.getTaskId());
        return ActionResult.success("更新成功");
    }

    /**
     * @param zxglAiResponsibilityCallBack
     * @return
     * @throws DataException
     */
    @PostMapping("/allocateResponsibilityCallback")
    @Transactional
    public ActionResult allocateResponsibilityCallback(@RequestBody ZXGL_AI_ResponsibilityCallBack zxglAiResponsibilityCallBack) throws DataException {
        log.info("allocateResponsibilityCallback----------------------------》回调已经成功");
        ZXGL_XMCFZGBMJS_MingXiEntity entity = zXGL_XMCFZGBMJS_MingXiService.getById(zxglAiResponsibilityCallBack.getFlowId());
        if (entity != null) {
            entity.setQtry(zxglAiResponsibilityCallBack.getReturnJson().getLeadPersonnel().getId());
            entity.setZrr(zxglAiResponsibilityCallBack.getReturnJson().getProjectManagers().getId());
            entity.setXzr(zxglAiResponsibilityCallBack.getReturnJson().getCollaborators().getId());
            zXGL_XMCFZGBMJS_MingXiService.updateById(entity);
            return ActionResult.success("更新成功");
        }
        return ActionResult.fail("更新失败，数据不存在");
    }


}
